package com.sicnu.demo07

import android.graphics.Color
import android.view.Gravity
import android.view.ViewGroup
import android.widget.Button
import androidx.recyclerview.widget.RecyclerView
import com.sicnu.demo07.model.Card

class CardAdapter(
    private val cards: List<Card>,
    private val onCardClick: (Int) -> Unit
) : RecyclerView.Adapter<CardAdapter.CardViewHolder>() {

    class CardViewHolder(val button: Button) : RecyclerView.ViewHolder(button)

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CardViewHolder {
        val button = Button(parent.context).apply {
            textSize = 18f
            setTextColor(Color.BLACK)
            gravity = Gravity.CENTER
            layoutParams = ViewGroup.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT,
                250 // 固定高度，减小卡片高度以便需要滚动
            )
        }
        return CardViewHolder(button)
    }

    override fun onBindViewHolder(holder: CardViewHolder, position: Int) {
        val card = cards[position]
        val button = holder.button
        
        when {
            card.isMatched -> {
                button.text = card.toString()
                button.setBackgroundColor(Color.GREEN)
                button.setTextColor(Color.WHITE)
                button.isEnabled = false
            }
            card.isChosen -> {
                button.text = card.toString()
                button.setBackgroundColor(Color.parseColor("#FFA500")) // Orange
                button.setTextColor(Color.BLACK)
                button.isEnabled = true
            }
            else -> {
                button.text = ""
                try {
                    button.setBackgroundResource(R.drawable.card_back)
                } catch (e: Exception) {
                    button.setBackgroundColor(Color.LTGRAY)
                    button.text = button.context.getString(R.string.card_back)
                }
                button.setTextColor(Color.BLACK)
                button.isEnabled = true
            }
        }
        
        button.setOnClickListener {
            onCardClick(position)
        }
    }

    override fun getItemCount(): Int = cards.size
}

